package com.example.goodpet.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.fragment.app.FragmentActivity;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.example.goodpet.R;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.DeviceUtil;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MapActivity extends FragmentActivity {

    private ImageView back;
    private PoiItem poiItem ;
    private Button btn_go;
    //地图容器
    private MapView mMapView;
    //地图控制器对象
    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(true)
                .colorRes(R.color.ic_back_background)
                .light(true)
                .apply();
        ActivityManager.getInstance().addActivity(this);

        poiItem = getIntent().getParcelableExtra("poiItem");
        mMapView = (MapView) findViewById(R.id.map);
        btn_go=findViewById(R.id.btn_go);
        back=findViewById(R.id.back);

        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        methodRequiresTwoPermission();
        initBluePoint();
        initMarker();
        initListener();

    }

    //动态申请权限
    @AfterPermissionGranted(0)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
                /*Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE*//*,
                Manifest.permission.READ_PHONE_STATE*/};

        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            // ...
            initLocation();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.location_rationale),
                    0, perms);
            methodRequiresTwoPermission();
        }
    }

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {

                    //可在其中解析amapLocation获取相应内容。
//                    rbHomeLocation.setText("测试");
//                    Log.e(TAG, "onLocationChanged: "+aMapLocation.getCity());
                    if(null!=aMapLocation.getCity()){
//                        rbHomeLocation.setText(aMapLocation.getCity());
                        MyApplication.location=aMapLocation.getCity();
                        MyApplication.locationId=aMapLocation.getCity();
                        MyApplication.locationSpecific=aMapLocation.getCity();
//                        Log.e(TAG, "onLocationChanged: "+MyApplication.location );
                    }else{
                        if(null!=aMapLocation.getAddress()){
                            MyApplication.locationSpecific=aMapLocation.getAddress();
                        }
                        MyApplication.location=aMapLocation.getProvince();
                        MyApplication.locationId=aMapLocation.getProvince();
                        MyApplication.locationSpecific=aMapLocation.getProvince();
//                        rbHomeLocation.setText(aMapLocation.getProvince());
                    }
                    MyApplication.longitude=aMapLocation.getLongitude();
                    MyApplication.latitude=aMapLocation.getLatitude();
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                    mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
//                    mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
                }
            }
        }
    };

    private void initLocation() {

        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

        AMapLocationClientOption option = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if(null != mLocationClient){
            mLocationClient.setLocationOption(option);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);

        //设置是否返回地址信息（默认返回地址信息）
//        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为true，允许模拟位置
//        mLocationOption.setMockEnable(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
//        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private void initListener() {
        btn_go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DeviceUtil.isInstall(MapActivity.this, "com.autonavi.minimap")) {// 是否安装了高德
                    Intent intents = new Intent();
                    intents.setData(Uri.parse("androidamap://navi?sourceApplication=goodpet&lat=" +
                            poiItem.getLatLonPoint().getLatitude() + "&lon=" + poiItem.getLatLonPoint().getLongitude() + "&dev=0&style=2"));
                    startActivity(intents); // 启动调用
                }
                else{
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    // 驾车导航
                    intent.setData(Uri.parse("http://uri.amap.com/navigation?from=" +
                            MyApplication.longitude + "," + MyApplication.latitude + "&to="+
                            poiItem.getLatLonPoint().getLongitude() + "," + poiItem.getLatLonPoint().getLatitude() + "&mode=car&src=nyx_super"));
                    startActivity(intent); // 启动调用
                }

            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void initMarker() {
//        Log.e(TAG, "onPoiSearched: "+poiItemV2.getTitle() );
        LatLonPoint latLonPoint = poiItem.getLatLonPoint();
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(new LatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude()));
        markerOption.title(poiItem.getTitle()).snippet(poiItem.getSnippet());

//            markerOption.draggable(true);//设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(),R.drawable.icon_location)));
//         将Marker设置为贴地显示，可以双指下拉地图查看效果
//        markerOption.setFlat(true);//设置marker平贴地图效果
        aMap.addMarker(markerOption);
      }

    private void initBluePoint() {
// 连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。

        //初始化定位蓝点样式类 定位一次，且将视角移动到地图中心点
            myLocationStyle = new MyLocationStyle().myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
            //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
//        myLocationStyle.interval(2000);
        //设置定位蓝点的icon图标方法，需要用到BitmapDescriptor类对象作为参数。
//        myLocationStyle.myLocationIcon(BitmapDescriptor myLocationIcon);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

}